package db

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"functime"
)

// --------------------
// Encode
// 用gob进行数据编码
//
func Encode(data interface{}) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	enc := gob.NewEncoder(buf)
	err := enc.Encode(data)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// -------------------
// Decode
// 用gob进行数据解码
//
func Decode(data []byte, to interface{}) error {
	buf := bytes.NewBuffer(data)
	dec := gob.NewDecoder(buf)
	err := dec.Decode(to)
	return err
}

var gobCache map[int][]byte = map[int][]byte{}

func Gob_InitData() {
	for i := 0; i < PlayerNum; i++ {
		uid := 1000 + i + 1

		_, found := gobCache[uid]
		if found {
			continue
		}

		user := NewUser(uid)

		b, err := Encode(user)
		if err != nil {
			fmt.Println("encode fail: " + err.Error())
		}

		gobCache[uid] = b
	}
}

func Gob_RunStress() {
	fc := functime.NewFuncTime()
	defer fc.End("Gob_RunStress")

	//	wg := sync.WaitGroup{}

	for n := 0; n < PlayerNum; n++ {
		//		wg.Add(1)
		func() {
			for i := 1; i <= FriendNum; i++ {
				uid := 1000 + i
				b := gobCache[uid]

				var user User
				if err := Decode(b, &user); err != nil {
					fmt.Println("decode fail: " + err.Error())
				}
				_ = user
				_ = b

				//				users = append(users, user)

				//								fmt.Println("memory get user:", user)
			}
			//			wg.Done()
		}()
	}

	//	wg.Wait()

	//	spew.Dump(users)
}
